package com.example.administrator.baikangxing.utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class CommomUtil {
    /**
     * 将JSONArray转换成一个bean集合
     * @param successJson
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> ArrayList<T> parserJsonArrayToList(JSONArray successJson, Class<T> cls) {
        try {
            ArrayList<T> list = new ArrayList();
            for(int i = 0; i < successJson.length(); i++){
                JSONObject jsonObject = successJson.getJSONObject(i);
                T t = GsonUtil.parseJsonToBean(jsonObject.toString(),cls);
                list.add(t);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将JSONArray转换成一个bean集合
     * @param str
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> ArrayList<T> parserStringToList(String str, Class<T> cls) {
        try {
            JSONArray successJson = new JSONArray(str);
            ArrayList<T> list = new ArrayList();
            for(int i = 0; i < successJson.length(); i++){
                JSONObject jsonObject = successJson.getJSONObject(i);
                T t = GsonUtil.parseJsonToBean(jsonObject.toString(),cls);
                list.add(t);
            }
            return list;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

}
